package com.hliushi.redis.task;

import com.hliushi.redis.config.Constants;
import com.hliushi.redis.controller.vo.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author llhuang10
 * @date 2021/8/10 16:04
 */
@Slf4j
@Service
public class TaskService {

    @Resource
    private RedisTemplate redisTemplate;


    /**
     *
     */
    @PostConstruct
    public void initJHS() {
        log.info("启动定时器.......");
        new Thread(this::runJhs).start();

    }

    /**
     * 模拟定时器, 定时把数据库的特价商品, 刷新到redis中
     */
    public void runJhs() {
        while (true) {
            List<Product> list = this.getProducts();
            // 先删除缓存中数据
            redisTemplate.delete(Constants.JHS_KEY);
            // 再使用redis list数据结构的lpush来实现存储
            redisTemplate.opsForList().leftPushAll(Constants.JHS_KEY, list);

            try {
                // 间隔一分钟, 执行一遍
                Thread.sleep(1000 * 60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("runJhs定时刷新..............");
        }
    }

    /**
     * 模拟从数据库读取100件特价商品, 用于加载到聚划算的页面中
     *
     * @return
     */
    private List<Product> getProducts() {
        List<Product> result = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            int num = random.nextInt(10000);
            result.add(new Product((long) num, "product" + i, i, "detail" + i));
        }

        return result;
    }
}
